package com.kara.woodAgent.agent.tool.aspect;

import dev.langchain4j.mcp.client.McpClient;
import dev.langchain4j.mcp.client.McpException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/4 09:34:40
 */
@Aspect
@Component
public class McpToolAspect {

	private final Map<String, McpClient> cache = new ConcurrentHashMap<>();

	@Around("@annotation(com.kara.woodAgent.agent.tool.provider.McpTool)")
	public McpClient aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {

		String methodName = pjp.getSignature().getName();
		String cacheKey = methodName + Arrays.toString(pjp.getArgs());

		// 检查缓存
		if (cache.containsKey(cacheKey)) {
			return cache.get(cacheKey);
		}

		// 执行目标方法
		Object result = pjp.proceed();

		// 处理返回值
		if (result instanceof McpClient client) {
			cache.put(cacheKey, client);
			return client;
		}
		throw new RuntimeException("@McpTool return value must be McpClient");
	}


}
